<template>
  <a-spin
      :loading="spinLoading"
      :size="35"
      class="w-[100%]"
      tip="正在处理, 请稍候..."
  >
    <div class="bg-white p-6 rounded-lg shadow-sm">
      <!-- 基本信息区域 -->
      <div class="mb-6">
        <h2 class="text-lg font-medium mb-4 text-[var(--color-text-1)]">基本信息</h2>
        <a-form
            ref="formRef"
            :model="form"
            :rules="rules"
            auto-label-width
            layout="vertical"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item field="contractTemplateName" label="模板名称" required>
                <a-input
                    v-model="form.contractTemplateName"
                    placeholder="请输入模板名称"
                    @input="hasFormChanged = true"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="contractTemplateType" label="模板类型" required>
                <a-select
                    v-model="form.contractTemplateType"
                    placeholder="请选择模板类型"
                    @change="hasFormChanged = true"
                >
                  <a-option v-for="(d, index) in dicts[proxy.DICT.lindiContractTemplateType]" :key="index" :label="d.dictValue"
                            :value="String(d.dictKey)" />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="status" label="状态" required>
                <a-select
                    v-model="form.status"
                    placeholder="请选择状态"
                    @change="hasFormChanged = true"
                >
                  <a-option :value="1">启用</a-option>
                  <a-option :value="0">禁用</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="contractDescription" label="模板描述">
                <a-textarea
                    v-model="form.contractDescription"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                    placeholder="请输入模板描述信息"
                    @input="hasFormChanged = true"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <!-- PDF模板上传 -->
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-item field="pdfTemplate" label="PDF模板文件">
                <div class="file-upload-container">
                  <!-- 已有模板文件展示区域 -->
                  <div v-if="existingFiles.length > 0" class="existing-files-container mb-4">
                    <div class="mb-2 flex items-center justify-between">
                      <div class="text-gray-500">
                        <icon-info-circle class="mr-1" /> 已上传模板文件
                      </div>
                    </div>
                    <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
                      <a-list-item v-for="file in existingFiles" :key="file.fileId">
                        <a-card class="file-card" hoverable>
                          <div class="flex items-start">
                            <div class="file-icon mr-3">
                              <a-avatar :size="40" shape="square">
                                <icon-file-pdf v-if="file.fileType === 'pdf'"/>
                                <icon-file-image v-else-if="['jpg', 'png', 'jpeg'].includes(file.fileType)"/>
                                <icon-file v-else/>
                              </a-avatar>
                            </div>
                            <div class="flex-1 overflow-hidden">
                              <div class="font-medium truncate mb-1">{{ file.fileName }}</div>
                              <div class="text-gray-500 text-xs mb-1">上传时间：{{ file.uploadTime || '未知' }}</div>
                              <div class="mt-2">
                                <a-space>
                                  <a-button size="mini" type="primary" @click="downloadFile(file)">
                                    <template #icon>
                                      <icon-download/>
                                    </template>
                                    下载
                                  </a-button>
                                  
                                  <a-button size="mini" type="outline" @click="previewFile(file)">
                                    <template #icon>
                                      <icon-eye/>
                                    </template>
                                    预览
                                  </a-button>

                                  <a-button 
                                    size="mini" 
                                    status="danger" 
                                    :loading="deleteFileLoading"
                                    @click="removeExistingFile(file)"
                                  >
                                    <template #icon>
                                      <icon-delete/>
                                    </template>
                                    {{ deleteFileLoading ? '删除中' : '删除' }}
                                  </a-button>
                                </a-space>
                              </div>
                            </div>
                          </div>
                        </a-card>
                      </a-list-item>
                    </a-list>
                  </div>

                  <uploadFile v-if="existingFiles.length === 0"
                      ref="pdfUploadFileRef"
                      :file-source="fs"
                      :limit="1"
                      :multiple="false"
                      accept=".pdf"
                      list-type="text"
                      source-type="proxy"
                      @upload-success="onUploadSuccess"
                  />
                </div>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 字段配置区域 -->
      <div class="mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-medium text-[var(--color-text-1)]">字段配置</h2>
          <a-button type="primary" @click="addField">
            <icon-plus/>
            添加字段
          </a-button>
        </div>
        
        <a-table
            :columns="fieldColumns"
            :data="form.fields"
            :pagination="false"
            :scroll="{ y: 400 }"
            row-key="id"
        >
          <template #fieldName="{ record, rowIndex }">
            <a-input
                v-model="record.fieldName"
                placeholder="请输入字段名称"
                @blur="validateField(rowIndex, 'fieldName')"
                @input="hasFormChanged = true"
            />
          </template>
          <template #fieldKey="{ record, rowIndex }">
            <a-input
                v-model="record.fieldKey"
                placeholder="请输入字段标识"
                @blur="validateField(rowIndex, 'fieldKey')"
                @input="hasFormChanged = true"
            />
          </template>
          <template #fieldType="{ record }">
            <a-select v-model="record.fieldType" placeholder="选择类型" @change="hasFormChanged = true">
              <a-option value="text">文本</a-option>
              <!-- <a-option value="number">数字</a-option>
              <a-option value="date">日期</a-option>
              <a-option value="select">下拉选择</a-option> -->
            </a-select>
          </template>
          <template #required="{ record }">
            <a-switch v-model="record.fieldRequire" :checked-value="1" :unchecked-value="0" @change="hasFormChanged = true"/>
          </template>
          <template #defaultValue="{ record }">
            <a-input
                v-model="record.defaultValue"
                placeholder="默认值"
                @input="hasFormChanged = true"
            />
          </template>
          <template #textFieldName="{ record }">
            <a-input
                v-model="record.textFieldName"
                placeholder="请输入文本域名称"
                size="small"
                @input="hasFormChanged = true"
            />
          </template>
          <template #operation="{ record, rowIndex }">
            <a-button
                size="mini"
                status="danger"
                type="text"
                @click="removeField(rowIndex)"
            >
              <icon-delete/>
              删除
            </a-button>
          </template>
        </a-table>
      </div>

      <!-- 按钮区域 -->
      <div class="flex justify-center mt-6">
        <a-space>
          <a-button type="primary" @click="onSubmit()">提交</a-button>
          <a-button @click="onCancel">取消</a-button>
        </a-space>
      </div>
    </div>




  </a-spin>
</template>

<script setup>
import {getCurrentInstance, reactive, ref, watch, nextTick, onMounted} from "vue";
import {IconUpload, IconEye, IconPlus, IconDelete, IconLocation, IconInfoCircle, IconFilePdf, IconFileImage, IconFile, IconDownload, IconCheck, IconClose} from "@arco-design/web-vue/es/icon";
import uploadFile from "~/components/uploadFile/index.vue";
import {
  addContractTemplateApi,
  updateContractTemplateByContractTemplateIdApi,
  getContractTemplateByContractTemplateIdApi,
  deleteContractTemplateFileByFileIdApi
} from "~/api/lindi/contractTemplate";
import {fileSource} from "~/utils/sys.js";
import {deleteFileApi} from "~/api/basic/file.js";




// 全局实例
const {proxy} = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([proxy.DICT.lindiContractTemplateType]);

// 定义props
const props = defineProps({
  params: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emit
const emit = defineEmits(["ok", "cancel"]);

// 加载状态
const spinLoading = ref(false);

// 表单引用
const formRef = ref(null);

// 文件上传引用
const pdfUploadFileRef = ref(null);

// 跟踪新上传的文件ID，用于取消时清理
const newUploadedFileIds = ref([]);

// 文件来源
const fs = fileSource.lindi_contract_template_file.key; // 使用合同模板文件的文件来源

// 是否为编辑模式
const isEdit = ref(false);

// 已有文件列表
const existingFiles = ref([]);





// 表单数据
const form = reactive({
  contractTemplateName: "",
  contractTemplateType: "",
  status: 1,
  contractDescription: "",
  contractTemplateFileId: "", // 合同模板文件ID
  fileIds: [], // 文件ID，使用数组存储
  fields: []
});

// 表单验证规则
const rules = {
  contractTemplateName: [
    {required: true, message: "模板名称不能为空"},
    {maxLength: 100, message: "模板名称长度不能超过100个字符"},
  ],
  contractTemplateType: [
    {required: true, message: "模板类型不能为空"},
  ],
  status: [
    {required: true, message: "状态不能为空"},
  ],
  contractDescription: [
    {maxLength: 500, message: "描述长度不能超过500个字符"},
  ],
};

// 字段表格列配置
const fieldColumns = [
  {title: "字段名称", dataIndex: "fieldName", slotName: "fieldName", width: 150},
  {title: "字段标识", dataIndex: "fieldKey", slotName: "fieldKey", width: 150},
  {title: "字段类型", dataIndex: "fieldType", slotName: "fieldType", width: 120},
  {title: "必填", dataIndex: "required", slotName: "required", width: 80, align: "center"},
  {title: "默认值", dataIndex: "defaultValue", slotName: "defaultValue", width: 120},
  {title: "文本域名称", dataIndex: "textFieldName", slotName: "textFieldName", width: 200},
  {title: "操作", dataIndex: "operation", slotName: "operation", width: 100, align: "center"},
];



// 监听参数变化
watch(
    () => props.params,
    () => {
      if (props.params.contractTemplateId) {
        isEdit.value = true;
        loadTemplateInfo(props.params.contractTemplateId);
      } else {
        isEdit.value = false;
        // 初始化一些默认字段
        initDefaultFields();
      }
    },
    {deep: true, immediate: true}
);





// 初始化默认字段
function initDefaultFields() {
  form.fields = [];
}

// 加载模板信息
function loadTemplateInfo(contractTemplateId) {
  spinLoading.value = true;
  
  getContractTemplateByContractTemplateIdApi(contractTemplateId)
    .then(res => {
        if (res) {
          // 处理后端返回的数据
          const data = {...res};
          
          // 处理文件ID
          if (typeof data.fileIds === 'string' && data.fileIds) {
            data.fileIds = data.fileIds.split(',');
          } else if (!Array.isArray(data.fileIds)) {
            data.fileIds = [];
          }
          
          // 处理文件，用于上传组件回显和已有文件展示
          if (data.contractTemplateFile) {
            console.log('后端返回的文件数据:', data.contractTemplateFile);
            
            // 更新已有文件列表，用于展示（转换为数组格式）
            existingFiles.value = [{
              fileId: data.contractTemplateFile.fileId,
              fileName: data.contractTemplateFile.fileName,
              fileUrl: data.contractTemplateFile.fileUrl,
              fileType: data.contractTemplateFile.fileType?.split('/')[1] || 'pdf',
              uploadTime: data.contractTemplateFile.createTime
            }];
            
            // 将文件数据转换为上传组件需要的格式
            const fileList = [{
              uid: data.contractTemplateFile.fileId,
              name: data.contractTemplateFile.fileName,
              url: data.contractTemplateFile.fileUrl, // 设置url用于预览
              status: 'done',
              response: {fileId: data.contractTemplateFile.fileId} // 设置response.fileId用于删除和获取文件ID
            }];
            
            console.log('转换后的文件列表:', fileList);
            // 设置文件上传组件的文件列表
            if (pdfUploadFileRef.value) {
              setTimeout(() => {
                pdfUploadFileRef.value.fileList = fileList;
              }, 0);
            }
            

          } else {
            // 如果没有文件，清空已有文件列表
            existingFiles.value = [];
          }
          
          Object.assign(form, data);
        } else {
          proxy.$message.error(res.msg || '获取合同模板详情失败');
        }
    })
    .catch(error => {
      console.error('加载模板信息失败:', error);
      proxy.$message.error('加载失败，请稍后重试');
    })
    .finally(() => {
      spinLoading.value = false;
    });
}

// 下载文件
function downloadFile(file) {
  window.open(file.fileUrl, '_blank');
}

// 预览文件
function previewFile(file) {
  // 直接在新窗口打开文件
  window.open(file.fileUrl, '_blank');
}

// 删除文件加载状态
const deleteFileLoading = ref(false);

// 表单变更状态跟踪
const hasFormChanged = ref(false);

// 删除已有文件
function removeExistingFile(file) {
  proxy.$modal.confirm({
    title: '确认删除',
    content: `确定要删除文件 "${file.fileName}" 吗？`,
    onOk: () => {
      deleteFileLoading.value = true;
      
      // 调用后端API删除文件
      deleteContractTemplateFileByFileIdApi(file.fileId)
        .then(() => {
          // 从已有文件列表中移除
          existingFiles.value = existingFiles.value.filter(item => item.fileId !== file.fileId);
          
          // 从上传组件的文件列表中移除
          if (pdfUploadFileRef.value && pdfUploadFileRef.value.fileList) {
            pdfUploadFileRef.value.fileList = pdfUploadFileRef.value.fileList.filter(
                item => item.uid !== file.fileId
            );
          }
          
          // 从表单的fileIds中移除
          if (form.fileIds && Array.isArray(form.fileIds)) {
            form.fileIds = form.fileIds.filter(id => id !== file.fileId);
          }
          
          // 清空合同模板文件ID（如果删除的是主文件）
           if (form.contractTemplateFileId === file.fileId) {
             form.contractTemplateFileId = '';
           }
           
           // 标记表单已变更
           hasFormChanged.value = true;
           
           proxy.$message.success('文件删除成功');
        })
        .catch(error => {
          console.error('删除文件失败:', error);
          proxy.$message.error('删除文件失败: ' + (error.message || '网络错误'));
        })
        .finally(() => {
          deleteFileLoading.value = false;
        });
    },
    onCancel: () => {
      // 用户取消删除操作
      console.log('用户取消删除文件操作');
    }
  });
}

// 添加字段
function addField() {
  const newField = {
    contractTemplateFieldId: null,
    contractTemplateId: null,
    fieldName: "",
    fieldKey: "",
    fieldType: "text",
    fieldRequire: 0,
    pageNumber: null,
    positionX: null,
    positionY: null,
    sortOrder: null,
    defaultValue: "",
    textFieldName: "",
    options: []
  };
  form.fields.push(newField);
  hasFormChanged.value = true;
}

// 删除字段
function removeField(index) {
  form.fields.splice(index, 1);
  hasFormChanged.value = true;
}

// 验证字段
function validateField(index, fieldName) {
  const field = form.fields[index];
  if (fieldName === 'fieldName' && !field.fieldName) {
    proxy.$message.warning('字段名称不能为空');
  }
  if (fieldName === 'fieldKey' && !field.fieldKey) {
    proxy.$message.warning('字段标识不能为空');
  }
}



// PDF文件上传成功回调
function onPdfUploadSuccess(response) {
  console.log('PDF文件上传成功:', response);
  console.log('响应数据结构:', JSON.stringify(response, null, 2));
  
  // 检查多种可能的响应字段
  let fileUrl = null;
  if (response) {
    // 常见的响应字段名
    fileUrl = response.fileUrl || response.url || response.data?.fileUrl || response.data?.url;
    
    // 如果响应中有data字段，也检查data内部
    if (response.data) {
      console.log('响应data字段:', response.data);
      fileUrl = fileUrl || response.data.fileUrl || response.data.url;
    }
    
    console.log('提取的文件URL:', fileUrl);
  }
  
  if (fileUrl) {
    proxy.$message.success('PDF文件上传成功');
    form.contractTemplateFileId = response.fileId;
  } else {
    console.error('未找到文件URL，响应结构:', response);
    proxy.$message.warning('PDF文件上传成功，但无法获取预览URL');
  }
}



// 提交表单
function onSubmit() {
  // 表单验证
  formRef.value.validate((valid) => {
    if (valid) {
      return false;
    }
    
    // 获取上传文件的ID数组
    const fileIdStr = pdfUploadFileRef.value?.getUploadFileId() || "";
    // 将逗号分隔的字符串转换为数组（如果为空则使用空数组）
    const newFileIds = fileIdStr ? fileIdStr.split(",") : [];
    
    // 合并已有文件ID和新上传的文件ID
    // 从existingFiles中获取文件ID
    const existingFileIds = existingFiles.value.map(file => file.fileId);
    
    // 合并去重
    form.fileIds = [...new Set([...existingFileIds, ...newFileIds])];
    
    // 注意：PDF模板文件不再是必填项，允许为空
    
    // 验证字段配置
    if (form.fields.length === 0) {
      proxy.$message.error('请至少配置一个字段');
      return;
    }
    
    // 验证字段完整性
    for (let i = 0; i < form.fields.length; i++) {
      const field = form.fields[i];
      if (!field.fieldName || !field.fieldKey) {
        proxy.$message.error(`第${i + 1}行字段信息不完整`);
        return;
      }
    }
    
    spinLoading.value = true;
    
    // 准备提交数据
    const submitData = {
      ...form
    };
    console.log(submitData)
    
    // 调用API
    const apiCall = isEdit.value 
      ? updateContractTemplateByContractTemplateIdApi(submitData)
      : addContractTemplateApi(submitData);
    
    apiCall
      .then(res => {
        // 由于axios响应拦截器已经处理了成功响应，这里直接处理成功逻辑
        if (isEdit.value) {
          proxy.$message.success('模板更新成功');
        } else {
          proxy.$message.success('模板创建成功');
        }
        newUploadedFileIds.value = []; // 清理文件ID列表
        hasFormChanged.value = false; // 重置表单变更状态
        emit("ok");
      })
      .catch(error => {
        console.error('提交失败:', error);
        proxy.$message.error('操作失败，请稍后重试');
      })
      .finally(() => {
        spinLoading.value = false;
      });
  });
}

// 取消
async function onCancel() {
  if (hasFormChanged.value) {
    proxy.$modal.confirm({
      title: '确认离开',
      content: '您有未保存的更改，确定要离开吗？',
      onOk: async () => {
        await cleanupUnusedFiles();
        emit("cancel");
      }
    });
  } else {
    await cleanupUnusedFiles();
    emit("cancel");
  }
}

// 清理未使用的文件
const cleanupUnusedFiles = async () => {
  for (const fileId of newUploadedFileIds.value) {
    try {
      await deleteFileApi(fileId);
    } catch (error) {
      console.error('删除文件失败:', error);
    }
  }
  newUploadedFileIds.value = [];
};

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  if (response && response.fileId && !isEdit.value) {
    newUploadedFileIds.value.push(response.fileId);
  }
};

// 合并的上传成功处理函数
const onUploadSuccess = (response) => {
  // 调用原有的PDF上传成功处理
  onPdfUploadSuccess(response);
  // 调用文件ID跟踪处理
  handleUploadSuccess(response);
  // 标记表单已变更
  hasFormChanged.value = true;
};
</script>

<style scoped>
.file-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-height: 120px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  border: 1px dashed #d1d5db;
  padding: 16px;
  background-color: #f9fafb;
}

.existing-files-container {
  width: 100%;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e5e7eb;
}

.file-card {
  background-color: #f8fafc;
  border-radius: 6px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.file-card:hover {
  background-color: #f1f5f9;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pdf-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.position-setting-container {
  height: 650px;
}

.cursor-crosshair {
  cursor: crosshair;
}

/* PDF.js 样式优化 - 确保PDF预览区域与内容范围一致 */
:deep(.vue-pdf-embed) {
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
}

:deep(.vue-pdf-embed canvas) {
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
  border: none !important;
}

/* 位置设置容器中的PDF样式 */
.pdf-position-container :deep(.vue-pdf-embed) {
  margin: 0 !important;
  padding: 0 !important;
  border: 1px solid #d1d5db;
}

.pdf-position-container :deep(.vue-pdf-embed canvas) {
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
  border: none !important;
}

/* 确保PDF容器没有额外的空白 */
.pdf-pages-container :deep(.vue-pdf-embed) {
  margin: 0 auto !important;
  padding: 0 !important;
}

.pdf-pages-container :deep(.vue-pdf-embed canvas) {
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
}


</style>